package com.abbas.abchat.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.abbas.abchat.AbChatApplication;
import com.abbas.abchat.entity.Account;

import java.util.Map;

/**
 * @author abbas
 * @description: TODO
 * @date 2022/4/13 21:20
 */
public class SpUtils {

//    private static Context mContext;
    private static SharedPreferences mSharedPreferences;
    private static SharedPreferences.Editor editor;
    private static SpUtils spUtils = new SpUtils();

    public static String LOGIN_ACCOUNT = "account";

    public String defaultValue = "";

    public static SpUtils config(Context context,String fileName){
//        mContext = context;
        mSharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
        editor = mSharedPreferences.edit();
        return spUtils;
    }

    public String getString(String key){
        return mSharedPreferences.getString(key,defaultValue);
    }

    public void putString(String key,String value){
        editor.putString(key,value);
        editor.apply();
    }

    public void putAccount(Account account) {
        putString(Account.ID,account.getId()+"");
        putString(Account.ACCOUNT,account.getAccount()+"");
        putString(Account.PASSWORD,account.getPassword()+"");
        putString(Account.NAME,account.getName()+"");
        putString(Account.CHAT_TABLE_DBNAME,account.getChatTableDbName()+"");
        putString(Account.IMAGE_PATH,account.getImgPath()+"");
    }

    public void autoLogin(Context context){
        Account account = new Account();
        try {
            account.setId(Integer.parseInt(getString(Account.ID)));
            account.setAccount(getString(Account.ACCOUNT));
            account.setPassword(getString(Account.PASSWORD));
            account.setName(getString(Account.NAME));
            account.setChatTableDbName(getString(Account.CHAT_TABLE_DBNAME));
            account.setImgPath(getString(Account.IMAGE_PATH));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        AbChatApplication.setAccount(account);
//        ChatTableDao chatTableDao = new ChatTableDaoImpl(context,account.getChatTableDbName());
//        try {
//            List<ChatTable> all = chatTableDao.findAll();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public void clear(){
        editor.clear();
        editor.apply();
    }

    public boolean isLogin(){
        if (!getString(Account.ID).equals(defaultValue)) return true;
        return false;
    }

    public Map<String, String> getAll(){
        return (Map<String, String>) mSharedPreferences.getAll();
    }
}
